from flask import Blueprint, render_template, jsonify, request,session
from models.entity.quarter import Quarter
from models.entity.department import Department
import json
from utils.nodetree import get_all_quarter
from utils.result import result

# 说明： 全部接口已经测试

mod = Blueprint("core_quarter", __name__, url_prefix="/core/quarter", template_folder="templates",
                static_folder="static")
@mod.route("/get_all/",methods=["GET", "POST"])
def get_department_all_interface():
    """
    以平铺方式返回所有岗位的json列表
    """
    # return: json
    # [
    #       {
    #               id: id,

    # ]
    rlist=[]
    for item in Quarter.get_all_quarters():
        t_dic = Quarter.get_quarter_dic(item)
        # t_dic=item.to_dict()
        rlist.append(t_dic)
    return result(data=rlist)



@mod.route('/get_tree_all/', methods=['GET', 'POST'])
def get_all_quarter_tree():
    """得到全部子区域"""
    try:
        data = json.loads(request.data.decode("utf-8"))
    except:
        return result(success=0,error_code=-1,error_msg='格式错误')
    id = data['id']
    tmp = {}
    paths = []
    all_tree_node = []
    quarter_root = Quarter.query.filter_by(department_id=id).filter_by(parent_id=0).all()  # 得到所有的根节点
    print('quarter_root', quarter_root)
    for item in quarter_root:
        t_list = []
        for t in Quarter.query.all():
            if t.path.split(',')[0] == str(item.id):
                print(t)
                print(1111)
                t_list.append(t)
        all_tree_node.append(t_list)
    rlist = []
    count = 0
    print(222)
    while count < len(quarter_root):
        rlist.append(get_all_quarter(all_tree_node[count], 0)[0])
        count += 1
    tmp['success'] = 1
    tmp['error_code'] = None
    tmp['error_msg'] = None
    tmp['data'] = rlist
    return jsonify(tmp)


@mod.route("/get_all_by_department_id/",methods=["GET", "POST"])
def get_department_all_by_department_id():
    """
    以平铺方式返回所有岗位的json列表
    """
    # return: json
    # [
    #       {
    #               department_id: 3,

    # ]
    try:
        dict = json.loads(request.data.decode("utf-8"))
        print('dict', dict)
    except:
        return result(success=0, error_code=-1, error_msg='格式错误')
    department_id = dict.get('department_id', '')
    rlist=[]
    for item in Quarter.get_all_quarters_by_department_id(department_id):
        t_dic = Quarter.get_quarter_dic(item)
        # t_dic=item.to_dict()
        rlist.append(t_dic)
    return result(data=rlist)


@mod.route('/add/', methods=['GET', 'POST'])
def add_quarter():
    """新增岗位"""
    """
    {
    "name":"董事长的长工",
    "description":"让别人活的",
    "code":"JCP2240dt",
    "dis_order":2,
    "create_time": 2018-8-28
    "department_id":3,
    "parent_id":1
    "status":1
    }
    """
    if request.method == 'POST':
        try:
            dict = json.loads(request.data.decode("utf-8"))
            print('dict', dict)
        except:
            return result(success=0, error_code=-1, error_msg='格式错误')
        if 'id' in dict:
            dict.pop('id')

        if not Department.query.filter_by(id=dict['department_id']).first():
            return result(success=0,error_code=-3,error_msg="部门不存在，请重新选择")
        # 这里应该添加Department的查询结果

        # creater_id = 1
        # if "id" in session:
        #     creater_id = session['auth']['user_id']

        quarter = Quarter()
        if Quarter.query.filter_by(name=dict['name']).filter_by(department_id=dict['department_id']).first():
            return result(success=0,error_code=-1,error_msg="岗位名称被占用，请重新定义")
        if Quarter.query.filter_by(code=dict['code']).first():
            return result(success=0,error_code=-1,error_msg="岗位编码被占用，请重新定义")
        if dict['parent_id']!= 0 and Quarter.get_quarter_by_id(dict['parent_id']).department_id != dict['department_id']:
            return result(success=0,error_code=-1,error_msg="部门，岗位数据有误")

        try:
            quarter.from_dict(dict)
        except RuntimeError as e:
            return result(success=0,error_code=-5,error_msg=str(e))
        if quarter.save():
            return result(success=1)
        else:
            return result(success=0,error_code=-3,error_msg='未知错误')



@mod.route('/del/', methods=['GET', 'POST'])
def del_quarter():
    """删除岗位"""
    """
    {
    "id": 2
    }
    """
    if request.method == 'POST':
        try:
            dict = json.loads(request.data.decode("utf-8"))
            print('dict', dict)
        except:
            return result(success=0, error_code=-1, error_msg='格式错误')
        id = dict['id']
        data = []
        tmp = {}
        if not Quarter.query.filter_by(id=id).first():
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "记录不存在，请重新选择"
            tmp['data'] = data
            return jsonify(tmp)
        if Quarter.query.filter_by(parent_id=id).first():
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "当前岗位存在下级，不能删除"
            tmp['data'] = data
            return jsonify(tmp)
        quarter = Quarter.get_quarter_by_id(id)
        if quarter.delete():
            tmp['success'] = 1
            tmp['error_code'] = None
            tmp['error_msg'] = None
            tmp['data'] = data
            return jsonify(tmp)
        else:
            tmp['success'] = 0
            tmp['error_code'] = -1
            tmp['error_msg'] = "未知错误"
            tmp['data'] = data
            return jsonify(tmp)


@mod.route('/edit/', methods=['GET', 'POST'])
def edit_quarter():
    """编辑quart"""
    """
    {
    "id":1,
    "name":"董事长的长工",
    "description":"让别人活的",
    "code":"JCP2240dt",
    "dis_order":2,
    "create_time": 2018-8-28
    "department_id":3,
    "parent_id":1
    "status":1
    }
    """
    if request.method == 'POST':
        try:
            dict = json.loads(request.data.decode("utf-8"))
            print('dict', dict)
        except:
            return result(success=0, error_code=-1, error_msg='格式错误')
        # tmp = {}
        # data = []
        id = dict['id']
        # 得到部门数据
        department_id = dict['department_id']
        # 得到上级的数据
        parent_id = dict['parent_id']
        code = dict['code']
        name = dict['name']
        dis_order = dict['dis_order']
        description = dict['description']
        status = dict['status']
        create_time = dict['create_time']
        quarter = Quarter.get_quarter_by_id(id)
        try:
            quarter.from_dict(dict)
        except:
            return result(success=0, error_code=-2, error_msg="数据不完整，格式错误")
        res = quarter.edit(name,description,code,dis_order,parent_id,department_id,create_time,status)
        return jsonify(res)

@mod.route("/search/",methods=["POST"])
def quarter_search():
    """
    模糊搜索接口
    """
    # request: json
    # {
    #       "query_word":"query_word"
    # }
    try:
        data=json.loads(request.data.decode("utf-8"))
    except:
        error_msg={
                                        "success":0,
                                        "error_code":-1,
                                        "error_msg":"json格式错误"
                            }
        return jsonify(error_msg)
    if "query_word" in data:
        query_word=data["query_word"]
    else:
        error_msg={
                                        "success":0,
                                        "error_code":-2,
                                        "error_msg":"数据不完整"
                            }
        return jsonify(error_msg)
    rdic=Quarter.search(query_word)
    return jsonify(rdic)







